import json
import random
from django.conf import settings
from django.shortcuts import HttpResponseRedirect, HttpResponse
from phones import models
from phones.models import User, PicTest, UserInfo
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
from django.core.mail import send_mail
import time
import os

def reg(request):
    user_name = request.POST.get("user_name")
    password = request.POST.get("pwd")
    email = request.POST.get("email")
    status = 0

    seed = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    sa = []
    salt = ''
    for i in range(16):
        sa.append(random.choice(seed))
        salt = "".join(sa)

    t = time.time()
    l = str(t).split(".")
    f = "".join(l)

    activitiCode = salt + f[0:16]

    models.User.objects.create(u_name=user_name,u_email=email,u_password=password,u_status=status,u_activiticode=activitiCode)
    return HttpResponse(1)

def nameReg(request):
    user_name = request.POST.get("user_name")
    members = models.User.objects.values('u_name')
    for i in members:
        if i['u_name'] == user_name:
            return HttpResponse(1)
    return HttpResponse('ok')

def emailReg(request):
    email = request.POST.get("email")
    emails = models.User.objects.values('u_email')
    for i in emails:
        if i['u_email'] == email:
            return HttpResponse(1)
    return HttpResponse('ok')

def sendEmail(request):
    user_email = request.POST.get("email")
    print(user_email)

    userobj = models.User.objects.get(u_email=user_email)
    AC = userobj.u_activiticode

    msg = '请点击<a href="http://127.0.0.1:8000/activitionsuc/?actiCode=' + AC + '"  target="_blank">此处</a>激活，开启正式会员之旅'
    send_mail('注册激活','',settings.EMAIL_FROM,
              [user_email],
              html_message=msg)
    return HttpResponseRedirect("/static/testtesttesttest.html")

def activitionsuc(request):
    actiCode = request.GET.get("actiCode")
    try:
        obj = models.User.objects.get(u_activiticode=actiCode)
        obj.u_status = 1
        obj.save()
        models.UserInfo.objects.create(user_id=obj.id,ui_img="\static\media\def_img.jpg")
    except Exception as e:
        print(e)
        return HttpResponseRedirect("/static/fail.html")
    return HttpResponseRedirect("/static/testtesttesttest.html")

def login(request):
    name = request.POST.get("user_name")
    password = request.POST.get("pwd")

    yzm = request.POST.get('yzm1')
    verifycode = request.session['verifycode']

    names = models.User.objects.values('u_name')
    passwords = models.User.objects.values('u_password')
    status = models.User.objects.values('u_status')
    count = 0
    for i in names:
        if str(names[count]['u_name']) == str(name) and str(passwords[count]['u_password']) == str(password):
            if str(yzm).lower() == str(verifycode).lower():
                if status[count]['u_status'] == True:
                    resp = HttpResponse("ok")
                    # resp.set_cookie("username",name)
                    request.session['username'] = name
                    return resp
                else:
                    return HttpResponse("qingjihuo")
        count += 1
    return HttpResponse(1)

def logout(request):
    response = HttpResponseRedirect('/static/index.html')
    try:
        # response.delete_cookie('username')
        # username = request.COOKIES["username"]
        request.session.flush()
        # request.session.clear()
    except Exception as e:
        print(e)
    return response

def getSession(request):
    try:
        l = []
        username = request.session.get("username")
        uid = models.User.objects.get(u_name=username).id
        l.append(username)
        l.append(uid)
        jd = json.dumps(l)
        return HttpResponse(jd)
    except Exception as e:
        print(e)
        return HttpResponse(False)

def verify_code(request):
    #引入随机函数模块
    import random
    #定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    #定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象，ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
    font = ImageFont.truetype('arial.ttf', 23)
    #构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    #释放画笔
    del draw
    # 存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    #内存文件操作
    buf = BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')

def pic_handle(request):
    uid = request.POST.get("hidden_uid_name")
    timestamp = int(round(time.time()*1000))
    f1 = request.FILES.get('pic')
    # fname='%s/booktest/%s'%(settings.MEDIA_ROOT,f1.name)
    filename = str(timestamp)+".jpg"
    fname = '%s/%s' % (settings.MEDIA_ROOT,filename)
    url = '/static/media/%s'%(filename)
    with open(fname,'wb') as pic:
        for c in f1.chunks():
            pic.write(c)
        img = UserInfo.objects.get(user_id=uid)
        path = r"D:\PyCharm_workspace\Projects\PhoneStore" + img.ui_img
        if os.path.exists(path) and path!="D:\PyCharm_workspace\Projects\PhoneStore\static\media\def_img.jpg":
            os.remove(path)
        img.ui_img = url
        img.save()

    return HttpResponseRedirect('/static/security_center.html')

def pic_show(request):   #显示用户图片
    username = request.GET.get("username")
    pics = User.objects.get(u_name=username).u_img
    context = {'pic': pics}
    jsondata = json.dumps(context)
    return HttpResponse(jsondata)

def verifyCheck(request):
    yzm = request.GET.get('yzm')
    verifycode = request.session['verifycode']
    if str(yzm).lower() == str(verifycode).lower():
        return HttpResponse('ok')
    return HttpResponse("NO")

def addUserInfo(request):
    user_id = request.GET.get("user_id")
    gen = request.GET.get("gen")
    birth = request.GET.get("birth")
    hobby = request.GET.get("hobby")
    qq = request.GET.get("qq")
    wx = request.GET.get("wx")
    # if hobby == None:
    #     hobby = ""
    models.UserInfo.objects.filter(user_id=user_id).update(ui_gender=gen,ui_birthday=birth,ui_hobby=hobby,ui_qq=qq,ui_wx= wx)
    return HttpResponse(1)

def reviseByEmail(request):   #修改密码
    username = request.GET.get("username")
    new_pwd = request.GET.get("new_pwd")
    models.User.objects.filter(u_name=username).update(u_password=new_pwd)
    return HttpResponse(1)

def isRevisePwd(request):
    username = request.GET.get("username")
    input_pwd = request.GET.get("pwd")
    print(username,input_pwd)
    try:
        old_pwd = models.User.objects.get(u_name=username).u_password
        if str(input_pwd) == str(old_pwd):
            return HttpResponse(1)
        else:
            return HttpResponse(0)
    except Exception as e:
        print(e)
        return HttpResponse(-1)

def infoCollection(request):       #收藏表
    goods_id = request.GET.get("goods_id")
    user_id = request.GET.get("user_id")
    goods = models.PhoneInfo.objects.get(id=goods_id)
    models.Collection.objects.create(c_name=goods.p_title,c_img=goods.p_img,c_price=float(goods.p_price)*100,c_uerid=user_id,c_goodsid=goods_id)
    return HttpResponse(1)

def cancelCollection(request): #取消收藏
    user_id = request.GET.get("uid")
    goods_id = request.GET.get("gid")
    models.Collection.objects.get(c_goodsid=goods_id,c_uerid=user_id).delete()
    return HttpResponse(1)

def showCollection(request):
    l = []
    uid = request.GET.get("uid")
    collections = models.Collection.objects.filter(c_uerid=uid)
    for i in collections:
        obj = {
            "name": i.c_name,
            "img": i.c_img,
            "price": i.c_price,
            "uid": i.c_uerid,
            "gid": i.c_goodsid,
        }
        l.append(obj)
    jd = json.dumps(l)
    return HttpResponse(jd)

def history(request):  #历史记录 超过20条就删除最开始的那条
    goods_id = request.GET.get("goods_id")
    user_id = request.GET.get("user_id")
    goods = models.PhoneInfo.objects.get(id=goods_id)
    models.History.objects.create(h_userid=user_id,h_title=goods.p_title,h_price=float(goods.p_price)*100,h_goodsid=goods_id,h_img=goods.p_img)
    alldata = models.History.objects.all()
    if len(alldata) > 20:
        for i in alldata[0:len(alldata)-1-19]:
            i.delete()
    return HttpResponse(1)

def delHistory(request):  #删除一条历史记录
    user_id = request.GET.get("user_id")
    goods_id = request.GET.get("goods_id")
    models.History.objects.filter(h_userid=user_id,h_goodsid=goods_id).delete()
    return HttpResponse(1)

def fillUI(request):
    uid = request.GET.get("user_id")
    user_info = models.UserInfo.objects.get(user_id=uid)
    obj = {
        "birth": user_info.ui_birthday,
        "gen": user_info.ui_gender,
        "hobby": user_info.ui_hobby,
        "wx": user_info.ui_wx,
        "qq": user_info.ui_qq,
        "img":user_info.ui_img
    }
    jd = json.dumps(obj)
    return HttpResponse(jd)

def showHistory(request):
    l = []
    uid = request.GET.get("uid")
    goods = models.History.objects.filter(h_userid=uid)
    for i in goods:
        obj = {
            "title": i.h_title,
            "price": i.h_price,
            "img":i.h_img,
            "userid": i.h_userid,
            "goodsid": i.h_goodsid,
        }
        l.append(obj)
    jd = json.dumps(l)
    return HttpResponse(jd)

def suanfa(request):
    l = []
    info = models.Comparation.objects.all()
    for i in info:
        prices = i.co_price
        romfee = prices*15/10000
        ramfee = prices*20/10000
        screenfee = prices*15/10000
        resolutionfee = prices*15/10000
        weightfee = prices*5/10000
        bcamerafee = prices*15/10000
        fcamerafee = prices*15/10000

        rom_num = i.co_rom.split("GB")[0]
        ram_num = i.co_ram.split("GB")[0]
        screen_num = i.co_mainScreen.split("英寸")[0]
        bcamera = i.co_bcamera.split("万像素")[0]
        fcamera = i.co_fcamera.split("万像素")[0]
        weight = i.co_weight.split("g")[0]
        weight = weight.split("k")[0]
        resolution = i.co_resolution
        if ram_num == "其它内存" or rom_num == "其它存储" or screen_num == "其它" or bcamera == "其他"\
             or bcamera == "无后置摄像头" or fcamera == "无前置摄像头" or fcamera == "其他" or weight == "其它分辨率" or weight == "其它":
            return HttpResponse("参数不全,无法比价")
        romf = float(str(romfee/int(rom_num))[0:5])
        ramf = float(str(ramfee/int(ram_num))[0:5])
        screenf = float(str(screenfee/float(screen_num))[0:5])
        bcameraf = float(str(bcamerafee/int(float(bcamera)))[0:5])
        fcameraf = float(str(fcamerafee/int(float(fcamera)))[0:5])
        weightf = float(str(weightfee/float(weight))[0:5])

        aromf = int(romf*1000)/336/10
        aromf = float("%.3f" %aromf)
        aramf = int(ramf*1000)/9329/10
        aramf = float("%.3f" % aramf)
        ascreenf = int(screenf*1000)/7335/10
        ascreenf = float("%.3f" % ascreenf)
        abcameraf = int(bcameraf*1000)/13/10
        abcameraf = float("%.3f" % abcameraf)
        afcameraf = int(fcameraf*1000)/22/10
        afcameraf = float("%.3f" % afcameraf)
        aweightf = int(weightf*1000)/62/10
        aweightf = float("%.3f" % aweightf)
        aweightf = -float(aweightf)
        resolutionf = resolution

        if resolutionf == "标清SD":
            resolutionf = float(str(4/6.38)[0:5])
        if resolutionf == "高清HD+":
            resolutionf = float(str(6/6.38)[0:5])
        if resolutionf == "全高清FHD+":
            resolutionf = float(str(8/6.38)[0:5])
        if resolutionf == "QHD+及以上":
            resolutionf = float(str(10/6.38)[0:5])

        one_score = round(aramf*20+aromf*15+ascreenf*15+abcameraf*15+aweightf*5+resolutionf*15+afcameraf*15,4)
        l.append(str(one_score) + "   ")
        # print(aramf,aromf,ascreenf,abcameraf,afcameraf,aweightf,resolutionf)
    jd = json.dumps(l)
    return HttpResponse(jd)#数值越小越好


#数据库手机平均价：3032
# RAM:0.2(606.4)(93.29)
# ROM:0.15(454.8)(3.36)
# screen:0.15(454.8)(73.35)
# resolution:0.15(454.8)(6.38)
# weight:0.05(151.5)(0.62)
# bcamera:0.15(454.8)(0.13)
# fcamera:0.15(454.8)(0.22)


# RAM运存平均值：6.5
# ROM储存平均值：135.3
#screen平均值:6.2
#resolution:平均分6.383分（0，4，6，8，10）
#weight:244.6
#bcamera平均值:3470.4
#fcamera平均值:2000.8







